
import type { User } from '~/types/user'
import mock from '../users-example.json'
import { SortBy } from '~/types/enums'

export default defineEventHandler((event) => {
	const users = [...mock]
	let { filterQuery, sortBy, asc, page, perPage }: { filterQuery: string, sortBy: SortBy, asc: string, page: number, perPage: number } = getQuery(event)
	filterQuery = filterQuery?.toLowerCase()
	let filteredUsers: User[] = filterQuery ? users.filter((user: User) => user.name.toLowerCase().includes(filterQuery) || user.surname.toLowerCase().includes(filterQuery)) : users
	const start: number = (page - 1) * perPage
	const end = start + Number(perPage)
	const ascending: any = asc === 'true'
	const sort = (method: string, asc: boolean) => {
      if (method === SortBy.name) {
				return filteredUsers.sort((a, b) =>{

						if (a.name > b.name) {
							return asc ? 1 : -1 ;
						}
						if (a.name < b.name) {
							return asc ? -1 : 1 ; ;
						}
						return 0;
				})
      }
			
      if (method === SortBy.surname) {
				return filteredUsers.sort((a, b) =>{
						if (a.surname > b.surname) {
							return asc ? 1 : -1 ;
						}
						if (a.surname < b.surname) {
							return asc ? -1 : 1 ; ;
						}
						return 0;
				})
      }
			
      if (method === SortBy.status) {
				if (asc) {
					return filteredUsers.sort((a, b) => a.isActive === b.isActive ? 0 : a.isActive ? -1 : 1)
				} else {
					return filteredUsers.sort((a, b) => a.isActive === b.isActive ? 0 : a.isActive ? 1 : -1)
				}
      }
			return filteredUsers
}

return { users: sort(sortBy, ascending).slice(start, end), total: filteredUsers?.length }

})
